package com.tiza.xiaoyoubao.ui.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.orhanobut.hawk.Hawk;
import com.squareup.picasso.Picasso;
import com.tianze.library.base.BaseFragment;
import com.tianze.library.utils.ToastUtils;
import com.tianze.library.view.SimpleDialog;
import com.tiza.xiaoyoubao.MainActivity;
import com.tiza.xiaoyoubao.R;
import com.tiza.xiaoyoubao.app.Constants;
import com.tiza.xiaoyoubao.app.UIHelper;
import com.tiza.xiaoyoubao.entity.BrowseOperateInfo;
import com.tiza.xiaoyoubao.entity.BrowseTaskOrderInfo;
import com.tiza.xiaoyoubao.entity.InsertTaskInfo;
import com.tiza.xiaoyoubao.entity.UserInfo;
import com.tiza.xiaoyoubao.net.ApiHttpClient;
import com.tiza.xiaoyoubao.net.JsonCallback;
import com.tiza.xiaoyoubao.net.ResponseInfo;
import com.tiza.xiaoyoubao.network.BrowserTaskApi;
import com.tiza.xiaoyoubao.utils.BitmapUtils;
import com.tiza.xiaoyoubao.utils.DateUtils;
import com.tiza.xiaoyoubao.utils.ImageUtils;
import com.tiza.xiaoyoubao.utils.OtherUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Request;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static android.app.Activity.RESULT_OK;

/**
 * Created by mapple on 17/4/14.
 * 手机浏览任务 操作任务
 */

public class BrowseOperationTaskFragment extends BaseFragment {
    BrowseTaskOrderInfo mOrderInfo = Hawk.get(Constants.KEY_BROWSEMPTBTASKOEDER_INFO, (BrowseTaskOrderInfo) null);
    InsertTaskInfo mInsertTaskInfo = Hawk.get(Constants.KEY_INSERTTASK_INFO, (InsertTaskInfo) null);
    UserInfo userInfo = Hawk.get(Constants.KEY_USER_INFO, (UserInfo) null);

    private static final  String LOGTAG = "BrowseOperationTaskFragment";
    private final int REQUEST_IMAGE = 2;//选取多张照片
    private static final int SELECt_IMG_REQUESTCODE = 0x001;//选取一张照片

    //TODO   coderlyzz  手机浏览任务  操作任务页面

    @BindView(R.id.tv_shopName)
    TextView tv_shopName;
    @BindView(R.id.iv_image)
    ImageView iv_image;
    @BindView(R.id.tv_shopDescribe)
    TextView tv_shopDescribe;
    @BindView(R.id.tv_showPrice)
    TextView tv_showPrice;
    @BindView(R.id.tv_taskType)
    TextView tv_taskType;
    @BindView(R.id.tv_keyWord)
    TextView tv_keyWord;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.tv_city)
    TextView tv_city;
    @BindView(R.id.tv_priceInterval)
    TextView tv_priceInterval;
    @BindView(R.id.tv_additionalRequest)
    TextView tv_additionalRequest;


    @BindView(R.id.openTaobao)
    View openTaobaoView;//打开淘宝


    @BindView(R.id.iv_result)
    ImageView iv_result;//搜索


    @BindView(R.id.iv_head)
    ImageView iv_iv_head;//


    @BindView(R.id.iv_foot)
    ImageView iv_foot;

    @BindView(R.id.layout_ctrl1)
    View layout_ctrl1;

    @BindView(R.id.layout_ctrl2)
    View layout_ctrl2;

    @BindView(R.id.layout_ctrl3)
    View layout_ctrl3;


    @BindView(R.id.favorAddView1)
    View favorAddView1;

    @BindView(R.id.favorAddView2)
    View favorAddView2;

    @BindView(R.id.favorAddView3)
    View favorAddView3;


    @BindView(R.id.favorAddImg1)
    ImageView favorAddImg1;

    @BindView(R.id.favorAddImg2)
    ImageView favorAddImg2;

    @BindView(R.id.favorAddImg3)
    ImageView favorAddImg3;

    @BindView(R.id.tv_comit)
    TextView tv_comit;

    @BindView(R.id.tv_save)
    TextView tv_save;

    @BindView(R.id.tv_comit_three)
    TextView tv_comit_three;

    @BindView(R.id.view_browse_comit_three)
    View view_browse_comit_three;

    @BindView(R.id.view_browse_comit)
    View view_browse_comit;


    //单图片上传标记
    private String ivState;
    //多图片上传数
    private int maxNum = 0;
    //多图片上传按钮位置
    private int step = 0;

    /**
     * 当前选择的图片的路径
     */
    public String mImagePath;
    String[] proj = {MediaStore.MediaColumns.DATA};
    private List<Bitmap> bitmapList = new ArrayList<>();
    private List<String> finalSelectPaths = new ArrayList<>();
    ArrayList<Date> dateList = new ArrayList<>();
    private ArrayList<String> mSelectPath;

    private BrowseOperateInfo browseOperateInfo;

    //操作任务开始时间
    private Date date1;
    private String addTime;

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date;
    Date date2;
    long diff;
    Timer timer = new Timer();
    private boolean isOverTime = false;

    private String taskState, orderFlag;

    Bundle args;
    private String way, cid, orderid, addtime, buyerid, taskCode, reason, account, sellerID, endTime;
    File imgSearchResult, imgGoodsHeader, imgeGoodsFooter, imgFavorGoods, imgAddShopCar, imgFavorShop;

    Bitmap bitmapSearchResult, bitmapGoodsHeader, bitmapeGoodsFooter, bitmapFavorGoods, bitmapAddShopCar, bitmapFavorShop;
    private Integer cGood,cShopn,cAddGood = null;

    private String ScannContent;

    private String orderScann, userId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        args = getArguments();
        way = args.getString("way");
        Log.v(LOGTAG, "way=" + way);
        userId = userInfo.getWebzzCmsBuyerInfo().getUserid();
        if (way.equals("1")) {
            taskState = "1";
            cid = String.valueOf(mInsertTaskInfo.getCid());
            orderid = mInsertTaskInfo.getOrderid();
            buyerid = mInsertTaskInfo.getBuyerid();
            taskCode = mInsertTaskInfo.getTaskCode();
            account = mInsertTaskInfo.getAccount();
            sellerID = mInsertTaskInfo.getSellerid();
            addtime = DateUtils.getDateToStringSec(mInsertTaskInfo.getAddtime());
            endTime = DateUtils.getDateToStringSec(mInsertTaskInfo.getEndtime());
            Log.v(LOGTAG, "endTime" + endTime);
            timer.schedule(task, 1000, 1000);
            orderScann = mInsertTaskInfo.getOrderScann();
        } else if (way.equals("2")) {
            taskState = "2";
            browseOperateInfo = (BrowseOperateInfo) args.getSerializable("info");
            cid = String.valueOf(browseOperateInfo.getId());
            orderid = browseOperateInfo.getOrderid();
            taskCode = browseOperateInfo.getTaskCode();
            account = browseOperateInfo.getAccount();
            sellerID = browseOperateInfo.getSellerId();
            addtime = DateUtils.getDateToStringSec(browseOperateInfo.getAddTime());
            endTime = DateUtils.getDateToStringSec(browseOperateInfo.getEndTime());
            Log.v(LOGTAG, "endTime" + endTime);
            timer.schedule(task, 1000, 1000);
            orderScann = browseOperateInfo.getOrderScann();
        }
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        date = df.parse(df.format(new Date()));
                        date2 = df.parse(endTime);

                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Log.v(LOGTAG, "当前时间" + date.getTime() + "endTime" + date2.getTime());
                    diff = (date2.getTime() - date.getTime()) / 1000;
                    int mm = (int) diff;
                    Log.v(LOGTAG, "isOverTime" + isOverTime + "任务剩余时间" + mm);
                    tv_comit.setText("提交任务:" + "(任务剩余时间 " + mm + "S)");
                    if (diff <= 0) {
                        tv_comit.setText("提交任务:" + "(任务剩余时间 " + 0 + "S)");
                        view_browse_comit.setBackgroundColor(getResources().getColor(R.color.disabled));
                        tv_comit.setEnabled(false);
                        timer.cancel();
                        isOverTime = true;
                    }
                }
            });
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_browse_operation_task;
    }

    @Override
    protected void initData() {
        try {
            date1 = df.parse(addtime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void scannResult(String scannSetting) {
        Log.v(LOGTAG, scannSetting);
        if(null != scannSetting && !"".equals(scannSetting)) {
            String replaceStr = scannSetting.replaceAll("=",":");
            Log.v(LOGTAG, replaceStr);
            try {
                JSONObject jsonObject = new JSONObject(replaceStr);
                cGood = jsonObject.getInt("c_good");
                cShopn = jsonObject.getInt("c_shop");
                cAddGood = jsonObject.getInt("c_add_good");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Log.v(LOGTAG, cGood + "" + cShopn + cAddGood);
        boolean condition = (cGood != null && cShopn != null && cAddGood != null);
        boolean condition1 = (cGood == 0 && cShopn == 0 && cAddGood == 0);
        boolean condition2 = (cGood == 1 && cShopn == 1 && cAddGood == 1);
        boolean condition3 = (cGood == 0 && cShopn == 0 && cAddGood == 1);
        boolean condition4 = (cGood == 0 && cShopn == 1 && cAddGood == 0);
        boolean condition5 = (cGood == 1 && cShopn == 0 && cAddGood == 0);
        boolean condition6 = (cGood == 1 && cShopn == 1 && cAddGood == 0);
        boolean condition7 = (cGood == 1 && cShopn == 0 && cAddGood == 1);
        boolean condition8 = (cGood == 0 && cShopn == 1 && cAddGood == 1);


        Log.v(LOGTAG, "condition" + condition +  "condition1" + condition1 + "condition2" + condition2 + "condition3" + condition3
                + "condition4" + condition4  + "condition5" + condition5 + "condition6" + condition6);
        if (condition) {
            if (condition1 || !"1".equals(orderScann)) {
                layout_ctrl1.setVisibility(View.GONE);
                layout_ctrl2.setVisibility(View.GONE);
                layout_ctrl3.setVisibility(View.GONE);
                view_browse_comit_three.setVisibility(View.GONE);
            }else if (condition2) {
                //nothing
            }else if (condition3) {
                favorAddView1.setVisibility(View.GONE);
                favorAddView3.setVisibility(View.GONE);
                view_browse_comit_three.setVisibility(View.GONE);
            }else if (condition4) {
                favorAddView1.setVisibility(View.GONE);
                favorAddView2.setVisibility(View.GONE);
                view_browse_comit_three.setVisibility(View.GONE);
            }else if (condition5) {
                favorAddView2.setVisibility(View.GONE);
                favorAddView3.setVisibility(View.GONE);
                view_browse_comit_three.setVisibility(View.GONE);
            }else if (condition6) {
                favorAddView2.setVisibility(View.GONE);
                tv_comit_three.setText("一次性上传2张图片");
            }else if (condition7) {
                favorAddView3.setVisibility(View.GONE);
                tv_comit_three.setText("一次性上传2张图片");
            }else if (condition8) {
                favorAddView1.setVisibility(View.GONE);
                tv_comit_three.setText("一次性上传2张图片");
            }
        }
    }

    @Override
    protected void initView() {
        try {
            date = df.parse(df.format(new Date()));
            date2 = df.parse(endTime);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        Log.v(LOGTAG, "当前时间" + date.getTime() + "endTime" + date2.getTime());
        diff = (date2.getTime() - date.getTime()) / 1000;
        int mm = (int) diff;
        Log.v(LOGTAG, "isOverTime" + isOverTime + "任务剩余时间" + mm);
        tv_comit.setText("提交任务:" + "(任务剩余时间 " + mm + "S)");
        if (diff <= 0) {
            tv_comit.setText("提交任务:" + "(任务剩余时间 " + 0 + "S)");
            view_browse_comit.setBackgroundColor(getResources().getColor(R.color.disabled));
            tv_comit.setEnabled(false);
        }
       if ("1".equals(way)) {
           Log.e(LOGTAG, "店铺名称" + mOrderInfo.getShopName() + "任务剩余时间" + mm);
            tv_shopName.setText(mOrderInfo.getShopName()
                    .replaceFirst(mOrderInfo.getShopName().substring(0, 1),
                            "*"
                    ));
            if (mOrderInfo.getTitle().length() <= 15) {
                tv_shopDescribe.setText(mOrderInfo.getTitle());
            } else {
                tv_shopDescribe.setText("***" + mOrderInfo.getTitle()
                        .substring(15,
                                mOrderInfo.getTitle()
                                        .length()
                        ));
            }
            tv_keyWord.setText(mOrderInfo.getKeywords());
            Picasso.with(mActivity).load(ApiHttpClient.URL2 + mOrderInfo.getImages()).placeholder(
                    R.mipmap.rwcx_jiazaizhong).error(R.mipmap.rwcx_jiazaizhong).into(iv_image);
            tv_taskType.setText(mOrderInfo.getTypeName());
           tv_showPrice.setText(mOrderInfo.getMobilePrice());
//        tv_xiaoliang.setText(mOrderInfo.getReceiving());
            tv_location.setText(mOrderInfo.getReceiving());
            tv_city.setText(mOrderInfo.getCity());
            tv_priceInterval.setText(mOrderInfo.getPriceSection());
            if (mOrderInfo.getRemarks().equals(" ")) {
                tv_additionalRequest.setText("商家无其他要求");
            } else {
                tv_additionalRequest.setText(mOrderInfo.getRemarks());
            }
           ScannContent = mOrderInfo.getScannSetting().toString();
           scannResult(ScannContent);
           Log.i(LOGTAG,"orderScann" + mOrderInfo.getOrderScann());
           if (!"1".equals(orderScann)) {
               layout_ctrl1.setVisibility(View.GONE);
               layout_ctrl2.setVisibility(View.GONE);
               layout_ctrl3.setVisibility(View.GONE);
               view_browse_comit_three.setVisibility(View.GONE);
           }
//        String settingTime = mOrderInfo.getorde();
        } else if ("2".equals(way)) {
            //String scannSetting = browseOperateInfo.getScannSetting().toString();
           tv_shopName.setText(browseOperateInfo.getShopName()
                   .replaceFirst(browseOperateInfo.getShopName().substring(0, 1),
                           "*"
                   ));
           if (browseOperateInfo.getTitle().length() <= 15) {
               tv_shopDescribe.setText(browseOperateInfo.getTitle());
           } else {
               tv_shopDescribe.setText("***" + browseOperateInfo.getTitle()
                       .substring(15,
                               browseOperateInfo.getTitle()
                                       .length()
                       ));
           }
           tv_keyWord.setText(browseOperateInfo.getKeywords());
           Picasso.with(mActivity).load(ApiHttpClient.URL2 + browseOperateInfo.getImages()).placeholder(
                   R.mipmap.rwcx_jiazaizhong).error(R.mipmap.rwcx_jiazaizhong).into(iv_image);
           tv_taskType.setText(browseOperateInfo.getTypeName());
           tv_showPrice.setText(browseOperateInfo.getMobilePrice());
//        tv_xiaoliang.setText(mOrderInfo.getReceiving());
           tv_location.setText(browseOperateInfo.getReceiving());
           tv_city.setText(browseOperateInfo.getCity());
           tv_priceInterval.setText(browseOperateInfo.getPriceSection());
           if (browseOperateInfo.getRemarks().equals(" ")) {
               tv_additionalRequest.setText("商家无其他要求");
           } else {
               tv_additionalRequest.setText(browseOperateInfo.getRemarks());
           }


           ScannContent = browseOperateInfo.getScannSetting().toString();
           scannResult(ScannContent);
           Log.i(LOGTAG,"orderScann" + browseOperateInfo.getOrderScann());
           if (!"1".equals(orderScann)) {
               layout_ctrl1.setVisibility(View.GONE);
               layout_ctrl2.setVisibility(View.GONE);
               layout_ctrl3.setVisibility(View.GONE);
               view_browse_comit_three.setVisibility(View.GONE);
           }
        }
        openTaobaoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OtherUtils.copy(mOrderInfo.getKeywords(), mActivity);
                try {
                    PackageManager packageManager = mActivity.getPackageManager();
                    Intent intent = packageManager.getLaunchIntentForPackage("com.taobao.taobao");
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    toast("您未安装手机淘宝客户端,请先安装");
                }
            }
        });
    }

    public void upLoadImage(final String imageState) {
        Log.v(LOGTAG, "upLoadImage---imageState" + imageState);
        ivState = imageState;
        pickPhoto();
    }


    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        getActivity().startActivityForResult(intent, SELECT_IMAGE_RESULT_CODE);
        Log.v(LOGTAG, "pickPhoto");
    }


    @Override
    public boolean onBackPressed() {
        showCustomConfirmDialog("返回后台后将不保存所做操作，下次需要重新上传截图哦，确定要返回吗", "确定", "取消",
                new SimpleDialog.OnSimpleClickListener() {
                    @Override
                    public void onClick(SimpleDialog simpleDialog) {
                        Log.v(LOGTAG, "isOverTime" + isOverTime);
                        if (isOverTime) {
                            UIHelper.show(getActivity(), MainActivity.class, true);
                        } else {
                            orderFlag = "1";
                            upDateTask();
                        }
                        timer.cancel();
                        simpleDialog.dismiss();
                    }
                }, new SimpleDialog.OnSimpleClickListener() {
                    @Override
                    public void onClick(SimpleDialog simpleDialog) {
                        simpleDialog.dismiss();
                    }
                }
        );
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(LOGTAG, "requestCode :" + requestCode + "----------------requestCode :" + resultCode + "------------------data :" + data);
        if (requestCode == SELECT_IMAGE_RESULT_CODE && resultCode == RESULT_OK) {
            String imgPath = null;
            Uri uri = null;
            Log.v(LOGTAG, "data.getData()" + data.getData());
            if (data != null && data.getData() != null) {
                uri = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(uri, proj, null, null,
                        null);
                if (cursor == null) {
                    uri = ImageUtils.getUri(getActivity(), data);
                }
                imgPath = ImageUtils.getFilePathByFileUri(getActivity(), uri);
                Log.v(LOGTAG, "imgPath :" + imgPath);
            } else {//无数据使用指定的图片路径
                imgPath = mImagePath;
                int i = ImageUtils.parseImageDegree(imgPath);
                System.out.println("旋转的角度:" + i);
                Log.v(LOGTAG, "imgPath :" + imgPath);
            }

            File file = new File(imgPath);
            Date date = new Date(file.lastModified());
            boolean result = (date.getTime() - date1.getTime()) / 1000 < 0;
            if ((date.getTime() - date1.getTime()) / 1000 < 0) {
                toast("请上传任务开始后的图片");
                return;
            }

            //获取图片缩略图，避免OOM
            Bitmap bitmap = ImageUtils.getImageThumbnail(imgPath, ImageUtils.getWidth(
                    getActivity().getApplicationContext()) / 3 - 5, ImageUtils.getWidth(
                            getActivity().getApplicationContext()) / 3 -5);

            if ("result".equals(ivState)) {
                imgSearchResult = new File(imgPath);
                bitmapSearchResult = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
                iv_result.setImageBitmap(bitmapSearchResult);
            } else if ("head".equals(ivState)) {
                imgGoodsHeader = new File(imgPath);
                bitmapGoodsHeader = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
                iv_iv_head.setImageBitmap(bitmapGoodsHeader);
            } else if ("foot".equals(ivState)) {
                imgeGoodsFooter = new File(imgPath);
                bitmapeGoodsFooter = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
               if (imgGoodsHeader != null) {
                   boolean outTime = (new Date(imgeGoodsFooter.lastModified()).getTime() - new Date(
                           imgGoodsHeader.lastModified()).getTime()) / 1000 < 120;
                    Log.i(LOGTAG, outTime + "");
                   if (outTime) {
                       toast("请按要求浏览商品");
                       return;
                   }
               }
                iv_foot.setImageBitmap(bitmapeGoodsFooter);
            } else if ("favorAddImg1".equals(ivState)) {
                imgFavorGoods = new File(imgPath);
                bitmapFavorGoods = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
                favorAddImg1.setImageBitmap(bitmapFavorGoods);
            } else if ("favorAddImg2".equals(ivState)) {
                imgAddShopCar = new File(imgPath);
                bitmapAddShopCar = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
                favorAddImg2.setImageBitmap(bitmapAddShopCar);
            } else if ("favorAddImg3".equals(ivState)) {
                imgFavorShop = new File(imgPath);
                bitmapFavorShop = ImageUtils.rotateBitmap(bitmap,
                        ImageUtils.parseImageDegree(imgPath));
                favorAddImg3.setImageBitmap(bitmapFavorShop);
            }
        }else if (requestCode == REQUEST_IMAGE && resultCode == RESULT_OK) {
            mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            for (String p : mSelectPath) {
                Log.v(LOGTAG, "mSelectPath" +p);
                //加入最后选择的集合
                finalSelectPaths.add(p);
                Log.e("路径", p);
                //加载缩略图
                Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromSd(p, 200, 240);
                bitmapList.add(bitmap);
            }
            for (int i = 0; i < finalSelectPaths.size(); i++) {
                File file = new File(finalSelectPaths.get(i));
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                Date date = new Date(file.lastModified());
                dateList.add(date);
                Log.i("截图时间", "截图文件：" + finalSelectPaths.get(i));
                Log.i("截图时间", "截图时间：" + df.format(date));
            }
            Log.i("路径长度", "存储时间长度：" + dateList.size() + "");
            Log.i("路径长度", "路径长度：" + finalSelectPaths.size() + "");
            Log.i("路径长度", "bitmapList长度：" + bitmapList.size() + "");

            if (step == 1) {
                if ((dateList.get(0).getTime() - date1.getTime()) / 1000 > 0 && (dateList.get(1)
                        .getTime() - date1
                        .getTime()) / 1000 > 0 && (dateList.get(2)
                        .getTime() - date1.getTime()) / 1000 > 0) {
                    if ((dateList.get(2).getTime() - dateList.get(1).getTime()) / 1000 > 120) {
                        imgSearchResult = new File(finalSelectPaths.get(0));
                        imgGoodsHeader = new File(finalSelectPaths.get(1));
                        imgeGoodsFooter = new File(finalSelectPaths.get(2));
                        iv_result.setImageBitmap(bitmapList.get(0));
                        iv_iv_head.setImageBitmap(bitmapList.get(1));
                        iv_foot.setImageBitmap(bitmapList.get(2));
                        bitmapSearchResult = bitmapList.get(0);
                        bitmapGoodsHeader = bitmapList.get(1);
                        bitmapeGoodsFooter = bitmapList.get(2);
                    } else {
                        toast("请按要求浏览商品");
                        return;
                    }
                } else {
                    toast("请上传任务开始后的图片");
                    return;
                }
            } else if (step == 2) {
                //批量上传类型
                int resultType = checkMessage();
                Log.i(LOGTAG, "checkMessage" + checkMessage() + "=-----------------=" + "step" + step);
                //condition1-不传
                //condition2-传三张
                //condition3-添加购物车
                //condition4-收藏店铺
                //condition5-收藏商店
                //condition6-收藏商品、收藏店铺
                //condition7-收藏商品、添加购物车
                //condition8-收藏店铺、添加购物车
                if (1 == maxNum) {
                    if (3 == resultType) {
                        imgAddShopCar = new File(finalSelectPaths.get(0));
                        favorAddImg2.setImageBitmap(bitmapList.get(0));
                        bitmapAddShopCar = bitmapList.get(0);
                    }
                    if (4 == resultType) {
                        imgFavorShop = new File(finalSelectPaths.get(0));
                        favorAddImg3.setImageBitmap(bitmapList.get(0));
                        bitmapFavorShop = bitmapList.get(0);
                    }
                    if (5 == resultType) {
                        imgFavorGoods = new File(finalSelectPaths.get(0));
                        favorAddImg1.setImageBitmap(bitmapList.get(0));
                        bitmapFavorGoods = bitmapList.get(0);
                    }
                } else if (maxNum == 2) {
                    if (6 == resultType) {
                        imgFavorGoods = new File(finalSelectPaths.get(0));
                        imgFavorShop = new File(finalSelectPaths.get(1));
                        favorAddImg1.setImageBitmap(bitmapList.get(0));
                        favorAddImg3.setImageBitmap(bitmapList.get(1));
                        bitmapFavorGoods = bitmapList.get(0);
                        bitmapFavorShop = bitmapList.get(1);
                    }
                    if (7 == resultType) {
                        imgFavorGoods = new File(finalSelectPaths.get(0));
                        imgAddShopCar = new File(finalSelectPaths.get(1));
                        favorAddImg1.setImageBitmap(bitmapList.get(0));
                        favorAddImg2.setImageBitmap(bitmapList.get(1));
                        bitmapFavorGoods = bitmapList.get(0);
                        bitmapAddShopCar = bitmapList.get(1);
                    }
                    if (8 == resultType) {
                        imgAddShopCar = new File(finalSelectPaths.get(0));
                        imgFavorShop = new File(finalSelectPaths.get(1));
                        favorAddImg2.setImageBitmap(bitmapList.get(0));
                        favorAddImg3.setImageBitmap(bitmapList.get(1));
                        bitmapAddShopCar = bitmapList.get(0);
                        bitmapFavorShop = bitmapList.get(1);
                    }
                } else if (maxNum == 3) {
                    if (2 == resultType) {
                        imgFavorGoods = new File(finalSelectPaths.get(0));
                        imgAddShopCar = new File(finalSelectPaths.get(1));
                        imgFavorShop = new File(finalSelectPaths.get(2));
                        favorAddImg1.setImageBitmap(bitmapList.get(0));
                        favorAddImg2.setImageBitmap(bitmapList.get(1));
                        favorAddImg3.setImageBitmap(bitmapList.get(2));
                        bitmapFavorGoods = bitmapList.get(0);
                        bitmapAddShopCar = bitmapList.get(1);
                        bitmapFavorShop = bitmapList.get(2);
                    }
                }
            }
        }
    }

    private ImageView selectImgView;

    @OnClick({
            R.id.iv_result,
            R.id.iv_head,
            R.id.iv_foot,
            R.id.favorAddImg1,
            R.id.favorAddImg2,
            R.id.favorAddImg3,
            R.id.tv_comit,
            R.id.tv_save,
            R.id.tv_comit_three
    })
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_result:
                upLoadImage("result");
                break;
            case R.id.iv_head:
                upLoadImage("head");
                break;
            case R.id.iv_foot:
                upLoadImage("foot");
                break;
            case R.id.favorAddImg1:
                upLoadImage("favorAddImg1");
                break;
            case R.id.favorAddImg2:
                upLoadImage("favorAddImg2");
                break;
            case R.id.favorAddImg3:
                upLoadImage("favorAddImg3");
                break;
            case R.id.tv_save:
                maxNum = 3;
                step = 1;
                selectGallery();
                break;
            case R.id.tv_comit_three:
                int result = checkMessage();
                Log.i(LOGTAG, "checkMessage" + result);
                if(!"1".equals(orderScann)) {
                    maxNum = 0;
                } else {
                    if (3 == result || 4 == result || 5 == result) {
                        maxNum = 1;
                    }else if (6 == result || 7 == result || 8 == result) {
                        maxNum = 2;
                    }else if (2 == result) {
                        maxNum = 3;
                    }else if (1 == result){
                        maxNum = 0;
                    }
                }
                step = 2;
                selectGallery();
                break;
            case R.id.tv_comit:
                commit();
                break;
            default:
                break;
        }
    }


    private void selectGallery() {
        if (bitmapList != null || bitmapList.size() > 0) {
            bitmapList.clear();
        }
        if (finalSelectPaths != null || finalSelectPaths.size() > 0) {
            finalSelectPaths.clear();
        }
        if (dateList != null || dateList.size() > 0) {
            dateList.clear();
        }
        Intent intent = new Intent(mActivity, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片,不显示
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式,选取多张
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE,
                MultiImageSelectorActivity.MODE_MULTI
        );
        //        // 默认选择
        //        if (mSelectPath != null && mSelectPath.size() > 0) {
        //            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        //        }
        getActivity().startActivityForResult(intent, REQUEST_IMAGE);
    }

    private void commit() {
        String message = checkImages();
        if (!TextUtils.isEmpty(message)) {
            toast(message);
            return;
        }
        if (isOverTime) {
            toast("无法提交，任务已超时");
        } else {
            int result = checkMessage();
            if (0 == result) {
                toast("浏览任务类型有误");
            }
            timer.cancel();
            Log.v(LOGTAG, "浏览任务类型:" + result);
            orderFlag = "2";
            taskState = "2";
            if (!"1".equals(orderScann)) {
                result = 1;
            }
            if (1 == result) {
                insertBrowseTask1();
            }
            if (2 == result) {
                insertBrowseTask2();
            }
            if (3 == result) {
                insertBrowseTask3();
            }
            if (4 == result) {
                insertBrowseTask4();
            }
            if (5 == result) {
                insertBrowseTask5();
            }
            if (6 == result) {
                insertBrowseTask6();
            }
            if (7 == result) {
                insertBrowseTask7();
            }
            if (8 == result) {
                insertBrowseTask8();
            }
        }
    }

    private String checkImages() {
        if (bitmapSearchResult == null || bitmapGoodsHeader == null || bitmapeGoodsFooter == null)
            return "请选择要上传的照片";
        int result = checkMessage();
        if(!"1".equals(orderScann)) {
            result = 1;
        }
        //result1-不传
        //result2-传三张
        //result3-添加购物车
        //result4-收藏店铺
        //result5-收藏商店
        //result6-收藏商品、收藏店铺
        //result7-收藏商品、添加购物车
        //result8-收藏店铺、添加购物车
        if (1 == result) {
            return "";
        }
        if (2 == result) {
            if (bitmapFavorGoods == null || bitmapAddShopCar == null || bitmapFavorShop == null) {
                return "请选择要上传的照片";
            }
        }
        if (3 == result) {
            if (bitmapAddShopCar == null) {
                return "请选择要上传的照片";
            }
        }
        if (4 == result) {
            if (bitmapFavorShop == null) {
                return "请选择要上传的照片";
            }
        }
        if (5 == result) {
            if (bitmapFavorGoods == null) {
                return "请选择要上传的照片";
            }
        }
        if (6 == result) {
            if (bitmapFavorGoods == null || bitmapFavorShop == null) {
                return "请选择要上传的照片";
            }
        }
        if (7 == result) {
            if (bitmapFavorGoods == null || bitmapAddShopCar == null) {
                return "请选择要上传的照片";
            }
        }
        if (8 == result) {
            if (bitmapAddShopCar == null || bitmapFavorShop == null) {
                return "请选择要上传的照片";
            }
        }
        return "";
    }

    private int checkMessage() {
        boolean condition = (cGood != null && cShopn != null && cAddGood != null);
        boolean condition1 = (cGood == 0 && cShopn == 0 && cAddGood == 0);
        boolean condition2 = (cGood == 1 && cShopn == 1 && cAddGood == 1);
        boolean condition3 = (cGood == 0 && cShopn == 0 && cAddGood == 1);
        boolean condition4 = (cGood == 0 && cShopn == 1 && cAddGood == 0);
        boolean condition5 = (cGood == 1 && cShopn == 0 && cAddGood == 0);
        boolean condition6 = (cGood == 1 && cShopn == 1 && cAddGood == 0);
        boolean condition7 = (cGood == 1 && cShopn == 0 && cAddGood == 1);
        boolean condition8 = (cGood == 0 && cShopn == 1 && cAddGood == 1);
        if (condition) {
            if (condition1) {
                return 1;
            }
            if (condition2) {
                return 2;
            }
            if (condition3) {
                return 3;
            }
            if (condition4) {
                return 4;
            }
            if (condition5) {
                return 5;
            }
            if (condition6) {
                return 6;
            }
            if (condition7) {
                return 7;
            }
            if (condition8) {
                return 8;
            }
        }
        return 0;
    }

    private void insertBrowseTask1() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                null,
                null,
                null,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask2() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                imgFavorGoods,
                imgAddShopCar,
                imgFavorShop,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask3() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                null,
                imgAddShopCar,
                null,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask4() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                null,
                null,
                imgFavorShop,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask5() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                imgFavorGoods,
                null,
                null,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask6() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                imgFavorGoods,
                null,
                imgFavorShop,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask7() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                imgFavorGoods,
                imgAddShopCar,
                null,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }

    private void insertBrowseTask8() {
        BrowserTaskApi.optionBrowserTask(
                cid,
                orderid,
                userId,
                imgSearchResult,
                imgGoodsHeader,
                imgeGoodsFooter,
                null,
                imgAddShopCar,
                imgFavorShop,
                "addTime",
                new StringCallback() {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                        showWaitingDialog();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                        hideWaitingDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.showShort(getActivity(), e.toString());
                        hideWaitingDialog();
                    }

                    @Override
                    public void onResponse(String response) {
//                {"Message":"参数错误","Code":1}
                        if(response.contains("\"Code\":1")){
                            ToastUtils.showShort(getActivity(), "照片选择不完整");
                        }
                        toast("任务提交成功");
                        upDateTask();
                        hideWaitingDialog();
                        finish();
                    }
                });
    }


    private void upDateTask() {
        ApiHttpClient.setUpdateTask(this, orderid, orderFlag,
                new JsonCallback<String>(String.class, true) {

                    @Override
                    public void onBefore(Request request) {
                        super.onBefore(request);
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        toast("网络连接失败,请稍后再试");
                    }

                    @Override
                    public void onResponse(ResponseInfo<String> response) {
                        int code = response.getCode();
                        String message = response.getMessage();
                        if (code == 1) {
                            showWarnDialog(message);
                            return;
                        }
                        Map<String, Object> _map = response.getFirstEntity();
                        Bundle args = new Bundle();
                        if ("1".equals(taskState)) {
                            args.putSerializable("info", mOrderInfo);
                            args.putString("state", "browseTb");
                            args.putString("time", addtime);
                            args.putString("orderid", orderid);
                            args.putString("buyerid", buyerid);
                             UIHelper.showBrowseMpTask2(mActivity, args);
                        } else if ("2".equals(taskState)) {
                            args.putSerializable("info", browseOperateInfo);
                            args.putString("state", "browseOperate");
                            args.putString("time", addtime);
                            args.putString("orderid", orderid);
                            args.putString("buyerid", buyerid);
                            UIHelper.showBrowseMpTask2(mActivity, args);
                        } else if ("3".equals(taskState)) {
                            args.putString("way", "2");
                            UIHelper.showBrowseUnComplate(mActivity, args);
                        }
                        finish();
                    }

                    @Override
                    public void onAfter() {
                        super.onAfter();
                    }
                }
        );
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
